<!--
 * @Descripttion:
 * @Author: zhengminjie,xiayujia
 * @Date: 2021-04-05 19:16:43
 * @LastEditors: xiayujia
 * @LastEditTime: 2021-06-30 11:37:14
-->
<template>
  <div class="app-container">
    <el-form :model="memberManager" ref="memberForm" v-show="showSearch" :inline="true">
      <el-form-item label="选择群组" prop="selectGroup">
        <el-select v-model="value" placeholder="选择我创建/管理的群组" @focus="selectgroup" @change="getList" clearable="">
          <el-option
            v-for="item in groupManagerList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-tooltip content="请先选择群组噢！" placement="top">
          <el-button
            type="primary"
            plain
            size="mini"
            icon="el-icon-search"
            @click="search"
          >查看成员</el-button>
        </el-tooltip>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini"
          icon="el-icon-circle-plus"
          @click="addmember=true"
        >添加成员</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-popover
          placement="top"
          width="160"
          v-model="deletemember">
          <p>你确定要删除该成员嘛？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="deletemember = false">取消</el-button>
            <el-button size="mini" type="text" @click="DeleteMember">确定</el-button>
          </div>
          <el-button
            type="danger"
            plain
            size="mini"
            icon="el-icon-delete"
            slot="reference"
            :disabled="multiple"
          >删除成员</el-button>
        </el-popover>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          size="mini"
          icon="el-icon-upload"
          @click="handleExport"
          :disabled="!this.groupid"
        >导出名单</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button 
          type="warning" 
          plain
          size="mini"
          icon="el-icon-download"
          @click="upload.open=true"
          :disabled="!this.groupid"
        >导入成员名单</el-button>
      </el-col>
      <right-toolbar  :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row>

    </el-row>

  <!-- 表格 -->
    <el-table v-loading="loading" :data="memberManagerList" @selection-change="handleSelectionChange">
      <el-table-column	type="selection"  width="55" align="center" />
      <el-table-column  prop="groupNum"	label="群号"  align="center" :show-overflow-tooltip="true" />
      <el-table-column	prop="userName" label="用户昵称"  align="center" :show-overflow-tooltip="true" />
      <el-table-column	prop="userIdentity" label="用户身份"  align="center" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            :disabled="ifAdmin"
            @click="powerRow(scope.row),power=true"
            >权限配置</el-button>
            <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="editRow(scope.row),editinfo=true"
            >消息修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="memberManager.pageNum"
      :limit.sync="memberManager.pageSize"
    />

    <!-- 添加成员对话框 -->
    <el-dialog title="添加成员" :visible.sync="addmember">
      <el-form :model="addMemberForm">
        <el-form-item label="群号" label-width="100px">
          <el-input v-model="addMemberForm.groupNum" disabled style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="用户名" label-width="100px">
          <el-input v-model="addMemberForm.userName" style="width:200px" placeholder="请输入要添加成员的用户名"></el-input>
        </el-form-item>
        <el-form-item style="text-align:center">
          <el-button type="primary" @click="AddMember">添 加</el-button>
          <el-button @click="addmember = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 权限配置对话框 -->
    <el-dialog title="权限配置" :visible.sync="power">
      <el-form :model="powerForm">
        <el-form-item label="设置用户身份">
          <el-radio-group v-model="powerForm.userIdentity">
            <el-radio label="管理员"></el-radio>
            <el-radio label="普通人"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="设置分发数据">
          <el-radio-group v-model="powerForm.dataDistribution">
            <el-radio label="可以分发数据" ></el-radio>
            <el-radio label="不能分发数据" ></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="text-align:center">
          <el-button type="primary" @click="Power">确 定</el-button>
          <el-button @click="power = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 信息修改对话框 -->
    <el-dialog title="成员信息修改" :visible.sync="editinfo" width="500px" center>
      <el-form :model="editForm">
        <el-form-item label="群号" label-width="140px">
          <el-input v-model="editForm.groupNum" style="width:200px" disabled></el-input>
        </el-form-item>
        <el-form-item label="成员用户名" label-width="140px">
          <el-input v-model="editForm.userName" style="width:200px" disabled></el-input>
        </el-form-item>
        <el-form-item label="设置群成员昵称" label-width="140px">
          <el-input v-model="editForm.groupUserName" style="width:200px"></el-input>
        </el-form-item>
        <el-form-item label="设置用户身份编号" label-width="140px">
          <el-input v-model="editForm.userNumber" style="width:200px"></el-input>
        </el-form-item>
        <el-form-item style="text-align:center">
          <el-button type="primary" @click="EditInfo">确 定</el-button>
          <el-button @click="editinfo = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 导入成员名单对话框 -->
    <el-dialog title="导入成员名单" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :data="paramsData"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-tooltip content="请先下载模板噢！" placement="top">
          <el-button type="primary" @click="DownloadGroup">确 定</el-button>
        </el-tooltip>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {selectGroup, getGroup,searchMember,addMember,deleteMember,powerConfig,editInfo,importTemplate,exportMember} from '@/api/distribution/memberManager'
import { getToken } from "@/utils/auth";

export default {
    name: "MemberManager",
    data(){
      return{
        // 是否是群创建人
        ifAdmin:false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        //删除按钮选中数组
        deleteids:[],
        //选中人员的用户身份
        userIdens:[],
        //选中人员的分发资格
        datadis:[],
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 添加成员
        addmember:false,
        addMemberForm:{
          groupNum:"",
          userName:"",
        },
        // 删除成员
        deletemember:false,
         // 导入成员名单
        downloadgroupForm:{},
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/distribution/personManager/importData"
        },
        // 权限配置
        power:false,
        editForm:{
          groupNum:"",
          userName:"",
          groupUserName:"",
          userNumber:"",
        },
        powerForm:{
          userIdentity:"",
          dataDistribution:"",
        },
        // 信息修改
        editinfo:false,
        // 群组数据
        groupManagerList:[],
        // 表格数据
        memberManagerList:[],
        // 总条数
        total: 0,
        //查询参数
        memberManager:{
            selectGroup:undefined,
            pageNum:1,
            pageSize:10,
        },
        // 选择群组的值
        value:"",
        //群组id
        groupid:"",
        //用户id
        userid:""
      }
    },
    created(){
      this.getList();
    },
    computed:{
      paramsData: function () {
        let params = {
          groupid:this.groupid          
        }
        return params
      }
    },
    methods:{
      /** 刷新列表 */
      getList(){
        this.loading = true;
        this.groupid=this.value;
        getGroup(this.value).then(res=>{
          this.memberManagerList=res.rows;
          let i=0;
            res.rows.forEach(item=>{
              this.memberManagerList.userName=item.userName;
              this.addMemberForm.groupNum=item.groupNum;
              this.editForm.groupNum=item.groupNum;
              if(item.userIdentity=="创建者")
              {
                this.memberManagerList.userIdentity="创建者";
              }
              else if(item.userIdentity=="管理员")
              {
                this.memberManagerList.userIdentity="管理员";
              }
            });
            this.loading=false;
        });
           this.memberManager.pageNum=1;
      },
      selectgroup(){
        selectGroup(this.userIdentity).then(res=>{
          this.groupManagerList = [];
          //console.log(res);
          let i=0;
          res.rows.forEach(element => {
            let member = {
              value:"",
              label:"",
              };
            member.value = element.groupId;
            member.label = element.groupName;
            this.groupManagerList.push(member);
            });
            this.loading = false;
          });
      },
      //查看成员
      search(){
        searchMember(this.groupid).then(res=>{
          this.memberManagerList=[];
          this.memberManagerList=res.rows;
          let i=0;
          res.rows.forEach(item=>{
            this.memberManagerList[i].groupNum=item.groupNum;           
              if(item.userIdentity=="创建者")
              {
                this.memberManagerList[i].userIdentity="创建者";      
              }
              else if(item.userIdentity=="管理员")
              {
                this.memberManagerList[i].userIdentity="管理员";
              }
              else if(item.userIdentity=="普通人")
              {
                this.memberManagerList[i].userIdentity="普通人";
              }
              i++;
          });
        });
      },
      //添加成员
      AddMember(){
        let userName="";
        let groupNum="";
        userName=this.addMemberForm.userName;
        groupNum=this.addMemberForm.groupNum;
        console.log(userName);
        console.log(groupNum);
        if(userName=="")
        {
          alert("请输入要添加成员的用户名");
        }
        else{
          addMember(groupNum,userName).then(res=>{
            console.log(res);
           if(res.msg=="该用户成员已存在该群组中"){
            this.$message({
              showClose: true,
              message: '该用户成员已存在该群组中，请重新输入',
              type:'error'
            });
          }
          else if(res.msg=="用户不存在"){
            this.$message({
              showClose: true,
              message: '用户不存在，请重新输入',
              type: 'error'
            });
          }
          else{
            this.$message({
              showClose: true,
              message: '添加成员成功',
              type: 'success'
            });
            this.search();
            this.addmember = false;
            this.addMemberForm.userName="";
            }
          })
        }
      },
      // 删除成员操作 
      DeleteMember(rows){
         let userId =[];
        if(rows.userId == undefined){
          userId = this.deleteids;
        }
        else{
           userName[0] = rows.userName;
        }
           console.log(userId);
           console.log(typeof userId);
         deleteMember(userId,this.groupid).then(res=>{
           console.log(res);
           if(res.msg=="删除成员成功"){
            this.$message({
              showClose: true,
              message: '删除成员成功',
              type:'success'
            });
           this.search();
           this.deletemember = false;
           }
        })
      },
      /** 配置权限操作 */
      powerRow(rows){
        this.powerForm.userIdentity=rows.userIdentity;
        this.powerForm.dataDistribution=rows.dataDistribution;
        this.userid=rows.userId;
        if(rows.dataDistribution)
        {
          this.powerForm.dataDistribution="可以分发数据";
        }
        else{
          this.powerForm.dataDistribution="不能分发数据";} 
        console.log(rows.userIdentity);
        console.log(rows.dataDistribution);
        console.log(this.powerForm.dataDistribution);
      },
      Power(rows){
          console.log(this.userid);
          let userIdentity="";
          let dataDistribution="";
          userIdentity=this.powerForm.userIdentity;
          if(this.powerForm.dataDistribution=="不能分发数据")
          {
            dataDistribution=false;
          }
          else
            dataDistribution=true;
          console.log(userIdentity);
          console.log(dataDistribution);
          powerConfig(this.userid,this.groupid,userIdentity,dataDistribution).then(res=>{
            console.log(res);
            if(res.msg=="不是创建者")
            {
              this.$message({
              showClose: true,
              message: '不是创建者，不能分配噢！',
              type:'error'
            });
            this.power=false;
            }
            if(res.msg=="权限配置成功"){
              this.$message({
                showClose: true,
                message: '权限配置成功',
                type:'success'
              });
            }
            this.search();
            this.power=false;
          })
        this.power = false;
      },
      //信息修改
      editRow(rows){
        this.editForm.userName=rows.userName;
        this.editForm.userNumber=rows.userNumber;
        this.editForm.groupUserName=rows.groupUserName;
        this.userid=rows.userId;
        console.log(this.groupid);
        console.log(this.userid);
      },
      EditInfo()
      {
        let usernum="";
        let groupusername="";
        groupusername=this.editForm.groupUserName;
        if(this.editForm.userNumber!=null)
          usernum=this.editForm.userNumber;
        else
          usernum="";
        console.log(groupusername);
        console.log(usernum);
        editInfo(this.userid,this.groupid,groupusername,usernum).then(res=>{
          console.log(res);
          if(res.msg=="不是创建者")
            {
              this.$message({
              showClose: true,
              message: '不是创建者，不能修改信息噢！',
              type:'error'
            });
            this.editinfo=false;
            }
            if(res.msg=="信息修改成功"){
              this.$message({
                showClose: true,
                message: '信息修改成功',
                type:'success'
              });
            }
            this.search();
            this.editinfo=false;
        })
        this.editinfo=false;
      },
     // 多选框选中数据
      handleSelectionChange(selection) {
        this.deleteids=selection.map(item=>item.userId)
        this.ids = selection.map(item => item.roleId)
        this.userIdens=selection.map(item=>item.userIdentity)
        this.datadis=selection.map(item=>item.dataDistribution)
        this.multiple = !selection.length
      },
      /** 导出按钮操作 */
      handleExport() {
        const groupid = this.groupid;
          this.$confirm('是否确认导出所有所选的群号成员数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportMember(groupid);
        }).then(response => {
          this.download(response.msg);
        })
      },
      /** 导入成员名单 */
      DownloadGroup(){
        this.$refs.upload.submit();
      },
      /** 下载模板操作 */
      importTemplate(){
        importTemplate().then(response => {
          this.download(response.msg);
        });
      },
      /** 文件上传中处理 */ 
      handleFileUploadProgress(event, file, fileList) {
        console.log(file);
        this.upload.isUploading = true;
      },
      /** 文件上传成功处理 */ 
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        this.search();
      },
    }
}
</script>
